package com.ws.shop.app;

import java.util.*;
import java.io.*;

public class Messages {

	private static final String CONFIG_FILE = "com/ws/shop/app/dbcp.properties";

	private static HashMap<String, String> resourceMap = new HashMap<String, String>();

	private static long lastTime;

	private static File f = null;

	public static String getString(String key) {

		try {
			String value = null;
			if (resourceMap.isEmpty()) {

				loadResource();
			}
			if (fileChanged()) {
				System.out.println("fileChanged()");

				loadResource();
			}

			value = (String) resourceMap.get(key);
			return value;
		} catch (Exception e) {
            e.printStackTrace();
			return null;
		}
	}

	private static void loadResource() throws IOException {
		resourceMap.clear();
		String resourceFile = Thread.currentThread().getContextClassLoader()
		.getResource(CONFIG_FILE).getFile();;
		System.out.println(resourceFile);
		f = new File(resourceFile);
		lastTime = f.lastModified();
		FileReader fr = new FileReader(resourceFile);
		BufferedReader br = new BufferedReader(fr);
		String line = "";
		String key = "";
		String value = "";

		while ((line = br.readLine()) != null) {
			if (line.startsWith("#") || line.indexOf("=") == -1) {
				continue;
			} else {
				key = line.substring(0, line.indexOf("="));
				value = line.substring(line.indexOf("=") + 1);
				resourceMap.put(key, value);
			}
		}

	}

	private static boolean fileChanged() {
		if (lastTime == f.lastModified())
			return false;
		else {
			lastTime = f.lastModified();
			return true;
		}
	}

	public static void main(String[] args) throws Exception {
		 String s= Thread.currentThread().getContextClassLoader()
		.getResource("com/hontoot/config/dbcp.properties").getFile();
		 System.out.println(s);
		String area = Messages.getString("db.maxActive");
		System.out.println(area);
	}

}